import { Component, OnInit } from '@angular/core';
import { SFRadioWidgetSchema, SFSchema, SFUISchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { Api } from 'src/app/shared/api/api';
import { DELETED_STATUS_ENUM, RESOURCE_METHOD_ENUM } from 'src/app/shared/constant/common-constant';
import { ResponseCode } from 'src/app/shared/response.code';

@Component({
  selector: 'app-system-resource-edit',
  templateUrl: './resource-edit.component.html'
})
export class ResourceEditComponent implements OnInit {
  record: any = {};
  deletedtatus: any[] = [];
  schema: SFSchema = {
    properties: {}
  };
  ui: SFUISchema = {
    '*': {
      spanLabel: 4,
      spanControl: 20
    }
  };

  constructor(private modal: NzModalRef, private msgSrv: NzMessageService, public http: _HttpClient) {
    this.record = this.modal.getConfig().nzComponentParams;
  }

  init() {
    this.deletedtatus = DELETED_STATUS_ENUM.filter(item => item.value !== null);
    this.schema = {
      properties: {
        resource: { type: 'string', title: '资源' },
        remark: { type: 'string', title: '备注' },
        method: {
          type: 'string',
          title: '方法',
          enum: RESOURCE_METHOD_ENUM,
          default: 'GET',
          ui: {
            widget: 'radio',
            styleType: 'button',
            buttonStyle: 'solid'
          } as SFRadioWidgetSchema
        },
        menuId: { type: 'string', title: '菜单', ui: { hidden: true } },
        deleted: {
          type: 'string',
          title: '状态',
          enum: this.deletedtatus,
          default: false,
          ui: {
            widget: 'radio',
            styleType: 'button',
            buttonStyle: 'solid'
          } as SFRadioWidgetSchema
        }
      },
      required: ['permission', 'deleted']
    };
  }

  ngOnInit() {
    this.init();
  }

  save(value: any) {
    if (this.record.id) {
      this.http.put(Api.BaseResourceApi, value).subscribe((res: any) => {
        if (res) {
          if (res.code === ResponseCode.SUCCESS) {
            this.msgSrv.success('修改成功');
            this.modal.close(true);
          } else {
            this.msgSrv.warning(res.message);
          }
        } else {
          this.msgSrv.error('修改失败，未知错误');
        }
      });
    } else {
      value.groupId = this.record.groupId;
      this.http.post(Api.BaseResourceApi, value).subscribe((res: any) => {
        if (res) {
          if (res.code === ResponseCode.SUCCESS) {
            this.msgSrv.success('保存成功');
            this.modal.close(true);
          } else {
            this.msgSrv.warning(res.message);
          }
        } else {
          this.msgSrv.error('保存失败，未知错误');
        }
      });
    }
  }

  close() {
    this.modal.destroy();
  }
}
